package com.qingzhu.component.lock.way.zookeeper.entity;

import com.qingzhu.component.lock.common.constant.AutoConfig;
import com.qingzhu.component.lock.common.entity.LockEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

/**
 * zookeeper 的锁实例封装
 * @author xiangjz
 * @version 1.0
 * @date 2021/1/14 17:07
 */
@Slf4j
public class ZookeeperLockEntity extends LockEntity<String> {

    private InterProcessMutex lock;

    public ZookeeperLockEntity(String lockKey, long expireTime) {
        this(lockKey, expireTime, null, null);
    }

    public ZookeeperLockEntity(String lockKey, long expireTime, CuratorFramework curatorFramework, String lockPath) {
        super(lockKey, expireTime);
        lock = new InterProcessMutex(curatorFramework, lockPath);
    }

    @Override
    public boolean doLock() {
        try {
            this.lock.acquire();
        } catch (Exception e) {
            log.error("{} lock of Zookeeper acquire failed, cause is {}", AutoConfig.COMPONENT_LOCK_LOG_PREFIX, e);
            return false;
        }
        return true;
    }

    @Override
    public void doUnlock() {
        try {
            this.lock.release();
        } catch (Exception e) {
            log.error("{} lock of Zookeeper release failed, cause is {}", AutoConfig.COMPONENT_LOCK_LOG_PREFIX, e);
        }
    }

}
